/**
 * overlay.js
 * Copyright (C) 2007-2011 Tommi Rautava
 * 
 * This file is part of Popmungo.
 *
 * Popmungo is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Popmungo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

org.mozdev.popmungo.classes.Overlay = function Overlay() {};

org.mozdev.popmungo.classes.Overlay.prototype = {
		
	requestCount: 0,
	
	listenerEnabled: false,
	
	contextMenuListenerEnabled: false,
	
	ignoredPages: {
		'cheater': true,
		'cn': true,
		'defaultconf': true,
		'defaultconfv2': true,
		'forumtop': true,
		'gazette': true,
		'menuforum': true,
		'pageexpired': true,
		'performancelive': true,
		'wallpaper': true
	},
	

	/**
	 * Process a game page.
	 *  
	 * @param {Document} aDocument
	 */
	handleContent: function handleContent(aDocument) {
		try {
			this.requestCount++;
			
			var timer1 = new org.mozdev.popmungo.classes.Timer("Request #"+ this.requestCount);
			var path1 = aDocument.location.pathname;
			var query1 = aDocument.location.search;

			org.mozdev.popmungo.logger.debug("Request #"+ this.requestCount +
				"\nhref="+ aDocument.location.href +
				"\npath="+ path1 +
				"\nquery="+ query1);

			// Remove frames
			if (path1 == '/common/index.html' && 
				org.mozdev.popmungo.logger.getTraceLevel()) 
			{
				var frames = aDocument.getElementsByTagName('frame');

				if (frames.length > 0) {
					var frame1 = frames[0];
					
					if (frame1.src) {
						org.mozdev.popmungo.logger.debug('Redirecting to '+ frame1.src);
						aDocument.location.replace(frame1.src);
					}
				}
				return;
			}

			org.mozdev.popmungo.ElementCache.clear();

			var page, action, action2;
			var result = path1.match(/\/([a-z0-9]+)\.asp/i);

			if (result) {
				page = result[1].toLowerCase();
			}
			
			result = query1.match(/[?&]action=([a-z0-9]+)/i);
			if (result) {
				action = result[1].toLowerCase();
			}

			result = query1.match(/[?&]action2=([a-z0-9]+)/i);
			if (result) {
				action2 = result[1].toLowerCase();
			}

			org.mozdev.popmungo.logger.debug("Request #"+ this.requestCount +
				"\npage="+ page +
				"\naction="+ action +
				"\naction2="+ action2);

			var processScoreNumbersEnabled = true;
			var processLinksEnabled = true;
	
			if (page == undefined) {
				org.mozdev.popmungo.logger.debug('Page undefined.');
				return;
			}
			else if (page == 'entry') {
				if (action == 'logout' ||
					action == 'sessiontimeout') 
				{
					org.mozdev.popmungo.UserSettings.LoggedOut(aDocument);
					org.mozdev.popmungo.logger.debug('Logged out.');
					return;
				}
				else if (action == undefined) {
					org.mozdev.popmungo.logger.debug('Not logged in.');
					return;
				}
			}
			else if (page == 'credits') {
				org.mozdev.popmungo.UserSettings.LoggedOut(aDocument);
				org.mozdev.popmungo.logger.debug('Logged out.');
				return;
			}
			else if (this.ignoredPages[page]) {
				org.mozdev.popmungo.logger.debug('Page ignored.');
				return;				
			}
			else if (page == 'choosecharacter') {
				if (org.mozdev.popmungo.UserSettings.charId) {
					org.mozdev.popmungo.UserSettings.LoggedOut(aDocument);
				}
				
				org.mozdev.popmungo.styles.appendCSS(aDocument);
				org.mozdev.popmungo.progressBars.addTextOverStats(aDocument);
				return;
			}

			var charId = org.mozdev.popmungo.UserSettings.getCharacterId(aDocument);
		
			if (charId) {
				// Save the current character. 
				org.mozdev.popmungo.prefs.setPref("extensions.popmungo.currentCharacter", charId);
				
				var langId = org.mozdev.popmungo.UserSettings.autoDetectLanguageFromPage(aDocument);
				
				org.mozdev.popmungo.strings.InitStringBundle(langId);
				
				org.mozdev.popmungo.logger.debug(timer1.elapsedTimeStr());

				org.mozdev.popmungo.logger.debug("Pre-tasks");

				org.mozdev.popmungo.styles.appendCSS(aDocument);
		
				org.mozdev.popmungo.logger.debug(timer1.elapsedTimeStr());

				org.mozdev.popmungo.logger.debug("Main-tasks");

				if (page == 'city') {
					if (action == 'view' ||
						action == undefined) 
					{
						org.mozdev.popmungo.locales.addLocaleIcons(aDocument);
						org.mozdev.popmungo.logger.debug(timer1.elapsedTimeStr());

						//org.mozdev.popmungo.UserSettings.updateSettingsFromCityPage(aDocument);
						org.mozdev.popmungo.traveling.addRouteInfoOnCityPage(aDocument);
						org.mozdev.popmungo.logger.debug(timer1.elapsedTimeStr());

						// Too many links here, we will need to use another method.
						processScoreNumbersEnabled = false;
						org.mozdev.popmungo.scoring.addNumericScoresOnCityPage(aDocument);
						org.mozdev.popmungo.logger.debug(timer1.elapsedTimeStr());

						processLinksEnabled = false;
						org.mozdev.popmungo.links.addEventHandlerOnCityPage(aDocument);
					}
					// online onlinesamelanguage newbies 
					// ongoingshows topchart viewfriends 
					// bookmarkedlocales
				}
				else if (page == 'user') {
					if (action == 'update') {
						org.mozdev.popmungo.UserSettings.updateSettingsOnLoad(aDocument);
					}
				}
				else if (page == 'performances') {
					if (action == undefined) {
						action = org.mozdev.popmungo.performances.identifyUndefinedPerformancesPage(aDocument);
					}
					
					if (action == 'arrangements') {
						org.mozdev.popmungo.performances.processArrangements(aDocument);
					} else if (action == 'readperformance') {
						org.mozdev.popmungo.performances.addTicketSalesStatistics(aDocument);
					} else if (action == 'citiesplayed') {
						org.mozdev.popmungo.performances.addSoldTicketsOnCitiesPage(aDocument);
					} else if (action == 'viewperformances') {
						org.mozdev.popmungo.performances.addSoldTicketsOnShowsPage(aDocument, false);
					} else if (action == 'clubcancelshow') {
						org.mozdev.popmungo.performances.processArrangements(aDocument);
					} else {
						// comingperformances clearallsetlists
						// accept confirmdiscardp setcancelperformance 
						org.mozdev.popmungo.performances.addSoldTicketsOnShowsPage(aDocument, true);
						org.mozdev.popmungo.Company.highlightCeoLocale(aDocument);
					}
				}
				else if (page == 'performancedetails') {
					// nextshow defaultsetlist viewperformance addsong
					// addaction removeaction
					org.mozdev.popmungo.progressBars.addTextOverStats(aDocument, org.mozdev.popmungo.progressBars.WITH_MINUS_SIGN_REGEXP);
					
					processLinksEnabled = false;
				}
				else if (page == 'company') {
					if (action == 'shows' && 
						!action2) 
					{
						org.mozdev.popmungo.progressBars.addTextOverTicketSalesBars(aDocument);
						org.mozdev.popmungo.performances.addTicketSalesTotalOnClubShowsPage(aDocument);
					} else if (action == 'restock') {
						org.mozdev.popmungo.products.highlightEmptyStockOnRestock(aDocument);
					} else if (action == 'manageproducts' ||
						action == 'deleteproductconfirm') 
					{
						org.mozdev.popmungo.products.highlightEmptyStockOnManageProducts(aDocument);
					} else if (action == undefined) {
						org.mozdev.popmungo.products.highlightEmptyStockIfFormPage(aDocument);
					}
					// SetBidLocale
				}
				else if (page == 'characterdetails') {
					if (action == undefined) {
						action = org.mozdev.popmungo.progressBars.identifyUndefinedCharacterDetailsPage(aDocument);
					}

					org.mozdev.popmungo.UserSettings.updateSettingsFromCharacterPage(aDocument);
					org.mozdev.popmungo.traveling.replaceWithLocalizedRouteNameOnPage(aDocument);

					if (action == 'view' || 
						action == undefined) 
					{
						org.mozdev.popmungo.Comparison.processCharacterSheet(aDocument);
					}
					else if (action == 'buddylist' ||
						action == 'deletefriend') 
					{
						org.mozdev.popmungo.Friends.highlightCityOnBuddyList(aDocument);
					}
					else if (action == 'relations' ||
						action == "abandonattachment") 
					{
						org.mozdev.popmungo.Friends.highlightCityOnRelationsPage(aDocument);
					}
					
					if (action == 'myskills' ||
						action == 'selectskill') {
						org.mozdev.popmungo.progressBars.addTextOverStats(aDocument, org.mozdev.popmungo.progressBars.PERCENTAGE_REGEXP);
					}
					else if (action == "apprentices" ||
						action == "removemaster" ||
						action == "removeapprentice") {
						org.mozdev.popmungo.progressBars.addTextOverStats(aDocument, org.mozdev.popmungo.progressBars.WITH_DECIMALS_REGEXP);
					}
					else {
						org.mozdev.popmungo.progressBars.addTextOverStats(aDocument);
					}

					// viewitems wear takeoff drop undress distributeexp
					// setpanda +myskills Influences ViewAssets Miscellaneous 
					// Photos Achievements CharacterPic Messages Calendar 
					// CurrencyConverter WorldClock readmessage AnswerMessage
					// +SelectSkill
				}
				else if (page == 'telephone') {
					org.mozdev.popmungo.progressBars.addTextOverStats(aDocument);
					org.mozdev.popmungo.Friends.highlightCityOnPhoneBook(aDocument);

					// undefined phonebook SendMessage OnlineShopping BookMarks 
					// NotePad Instructions FillCash Dial DeleteBM
				}
				else if (page == 'tribes') {
					if (action == 'members') {
						org.mozdev.popmungo.Friends.highlightCityOnTribeMembersList(aDocument);
					}
					
					// undefined TribeInfo Competitions Charts
				}
				else if (page == 'interact') {
					//org.mozdev.popmungo.Interaction.sortInteractionChoises(aDocument);
					org.mozdev.popmungo.progressBars.addTextOverStats(aDocument);
				}
				else if (page == 'relationshipdetails') {
					org.mozdev.popmungo.progressBars.addTextOverStats(aDocument);
				}
				else if (page == 'artist') {
					if (action == undefined ||
						action == 'view')
					{
						org.mozdev.popmungo.traveling.replaceWithLocalizedRouteNameOnPage(aDocument);
						org.mozdev.popmungo.traveling.addCityNameToBusStationName(aDocument);
					}

					// viewrepertoire popularity stagenames
					// setrepertoirepractise viewartistsong confirmdiscardas
					org.mozdev.popmungo.progressBars.addTextOverStats(aDocument, org.mozdev.popmungo.progressBars.WITH_MINUS_SIGN_REGEXP);
 				}
				else if (page == 'bookings') {
					if (action == undefined ||
						action == 'setdelete')
					{
						org.mozdev.popmungo.performances.addSoldTicketsOnSchedulePage(aDocument);
					}
					// QuickBook, SearchBookings, SearchJams, SearchStudio, Delete
				}
				else if (page == 'song') {
					// viewunfinished view viewsong deletesongconfirmed
					// setworkonsong undefined
					org.mozdev.popmungo.progressBars.addTextOverStats(aDocument);
				}
				else if (page == 'track') {
					// undefined viewtrack
					org.mozdev.popmungo.progressBars.addTextOverStats(aDocument);
				}
				else if (page == 'toursettings') {
					org.mozdev.popmungo.progressBars.addTextOverStats(aDocument);
					
					if (action == 'transport' ||
						action == 'addtransport' ||
						action == 'canceltransport') 
					{
						org.mozdev.popmungo.traveling.addTravelTimesOnTransportPage(aDocument);
						org.mozdev.popmungo.traveling.replaceWithLocalizedRouteNameOnPage(aDocument);
					}
					else if (action == 'equipment') {
						processLinksEnabled = false;
					}
				}
				else if (page == 'artistranking') {
					// undefined
					org.mozdev.popmungo.progressBars.addTextOverStats(aDocument);
				}
				else if (page == 'movies') {
					// viewmovie
					org.mozdev.popmungo.progressBars.addTextOverStats(aDocument);
				}
				else if (page == 'locale') {
					// cmd=confirmexchange (tour bus exchange)
					// viewshop useskills viewcharacters viewworkers
					org.mozdev.popmungo.progressBars.addTextOverStats(aDocument);
					if (action == 'view' || 
						action == undefined) 
					{
						org.mozdev.popmungo.traveling.addRouteInfoOnHighwayLocalePage(aDocument);
					}					
				}
				else if (page == 'competition') {
					if (action == 'schedule' ||
						action == 'deleteinvite' ||
						action == 'addopeninvite' ||
						action == 'setinviteartist')
					{
						org.mozdev.popmungo.Competitions.colorizeCompetitionEntries(aDocument);
					}
				}
				else if (page == 'distributeexp') {
					org.mozdev.popmungo.progressBars.addTextOverStats(aDocument);
				}
				else if (page == 'charts') {
					if (action == 'paparazzilist') {
						org.mozdev.popmungo.Friends.highlightCityOnPaparazziList(aDocument);
					}
					else if (action == 'topstarquality' ||
						action == 'artistrankings' ||
						action == 'topgenres') 
					{
						org.mozdev.popmungo.progressBars.addTextOverStats(aDocument);
					}
				}
				else if (page == 'charactervehicles')
				{
					if (action == 'viewvehicle' ||
						action == 'transferitem' ||
						action == 'pickupitem')
					{
						org.mozdev.popmungo.progressBars.addTextOverStats(aDocument);
					}
				}
				else {
					org.mozdev.popmungo.logger.debug("No actions");
				}
				// CharacterDiary/view
				// CharacterBlog/ReadBlog CreateBlogEntry

				org.mozdev.popmungo.logger.debug(timer1.elapsedTimeStr());

				org.mozdev.popmungo.logger.debug("Post-tasks");

				org.mozdev.popmungo.bookmarks.showBookmarks(aDocument);
				org.mozdev.popmungo.logger.debug(timer1.elapsedTimeStr());

				if (processScoreNumbersEnabled) {
					org.mozdev.popmungo.scoring.addNumericScores(aDocument);
					org.mozdev.popmungo.logger.debug(timer1.elapsedTimeStr());
				}
			
				if (processLinksEnabled) {
					org.mozdev.popmungo.links.processLinks(aDocument);
					org.mozdev.popmungo.logger.debug(timer1.elapsedTimeStr());
				}
			}
			else {
				org.mozdev.popmungo.logger.debug("Character ID is not available.");
			}
			
			org.mozdev.popmungo.logger.debug(timer1.elapsedTimeStr());
			org.mozdev.popmungo.logger.debug('Request #'+ this.requestCount + ' completed.');
		}
		catch (err)
		{
			org.mozdev.popmungo.logger.logError(err);
		}
	},
	

	isPopmundoDomain: function isPopmundoDomain(aDocument)
	{
		if (aDocument.location && 
			aDocument.location.protocol != 'about:')
		{
			return (null != aDocument.location.hostname.match(org.mozdev.popmungo.commonConstants.POPMUNDO_DOMAIN_REGEXP));
		}
		
		return false;
	},
	

	isPageLoadError: function (aDocument) {
		return (aDocument.documentURI.substr(0,14) == "about:neterror"); 		
	},


	onPageLoad: function onPageLoad(event) {
		var vDocument = event.originalTarget;

 		org.mozdev.popmungo.logger.debug("Target="+ vDocument);
 		
		if (vDocument instanceof HTMLDocument) {
			org.mozdev.popmungo.logger.debug("URL="+ vDocument.URL);		

			
			if (this.isPopmundoDomain(vDocument)) {
				if(!this.isPageLoadError(vDocument)) {
					this.handleContent(vDocument);
				}
				else {
		      		org.mozdev.popmungo.logger.debug("Page load error. Content ignored.");
				}
	      	}
	      	else {
	      		org.mozdev.popmungo.logger.debug("Domain ignored.");
	      	}
		}
		else {
			org.mozdev.popmungo.logger.debug("Target ignored.");
		}
	},

	
	handleEvent: function handleEvent(event) {
		org.mozdev.popmungo.logger.setTraceLevelFromPref();
		org.mozdev.popmungo.logger.debug("Event="+ event.type);
		
		switch (event.type) {
			case "DOMContentLoaded": 
				this.onPageLoad(event);
				break;
			case "load":
				this.init();
				break;
			case "unload":
				this.deinit();
				break;
			default: 
				org.mozdev.popmungo.logger.logError("Unexpected event: "+ event.type);
		}
	},


	init: function init() {
		this.logExtensionInfo();
		
		this.refreshUI();
		
		window.removeEventListener("load", this, false);

		org.mozdev.popmungo.prefs.addObserver("extensions.popmungo.enabled", this);
		org.mozdev.popmungo.prefs.addObserver("extensions.popmungo.traceLevel", this);
		
		org.mozdev.popmungo.prefs.addObserver("extensions.popmungo.options.scoring.colorNumber.gradientColor.from", org.mozdev.popmungo.scoring);
		org.mozdev.popmungo.prefs.addObserver("extensions.popmungo.options.scoring.colorNumber.gradientColor.to", org.mozdev.popmungo.scoring);
		
		org.mozdev.popmungo.prefs.addObserver("extensions.popmungo.characters.", org.mozdev.popmungo.UserSettings);
	},
	
	
	deinit: function deinit() {
		org.mozdev.popmungo.logger.debug("Unload extension.");
		
		org.mozdev.popmungo.prefs.removeObserver("extensions.popmungo.enabled", this);
		org.mozdev.popmungo.prefs.removeObserver("extensions.popmungo.traceLevel", this);
		
		org.mozdev.popmungo.prefs.removeObserver("extensions.popmungo.options.scoring.colorNumber.gradientColor.from", org.mozdev.popmungo.scoring);
		org.mozdev.popmungo.prefs.removeObserver("extensions.popmungo.options.scoring.colorNumber.gradientColor.to", org.mozdev.popmungo.scoring);
		
		org.mozdev.popmungo.prefs.removeObserver("extensions.popmungo.characters.", org.mozdev.popmungo.UserSettings);
		
		document.getElementById("appcontent").removeEventListener("DOMContentLoaded", this, true);

		window.removeEventListener("unload", this, false);
	},
	
	
	dateFormatSettingIsOutOfDate: function dateFormatSettingIsOutOfDate(dateFormatTypeId) {
		if (dateFormatTypeId) {
			org.mozdev.popmungo.prefs.setPref("extensions.popmungo.characters.<n>.dateFormatTypeId", dateFormatTypeId);
		}
	},
	
	
	logExtensionInfo: function logExtensionInfo() {
		try {
			var managerClass = Components.classes["@mozilla.org/extensions/manager;1"];
			
			if (managerClass)
			{
				var manager = managerClass.getService(Components.interfaces.nsIExtensionManager);
		
				var item = manager.getItemForID(org.mozdev.popmungo.commonConstants.GUID); //nsIUpdateItem
				var loc = manager.getInstallLocation(org.mozdev.popmungo.commonConstants.GUID); //nsIInstallLocation
				var canAccess = loc.canAccess ? " (writable)" : " (read-only)";
	
				org.mozdev.popmungo.logger.log(item.name +" "+ item.version);
				org.mozdev.popmungo.logger.debug( 
					"\nGUID: "+ item.id +
					"\nUpdateURL: "+ item.updateRDF +
					"\nTargetApp: "+ item.targetAppID +" "+ item.minAppVersion +"-"+ item.maxAppVersion +
					"\nInstallLoc: "+ loc.name + ", "+ loc.location.path + canAccess);
			}
			else {
				Components.utils.import("resource://gre/modules/AddonManager.jsm");
				
				if (AddonManager) {
					AddonManager.getAddonByID(org.mozdev.popmungo.commonConstants.GUID, this.logExtensionInfoCallback);
				}
				else {
					org.mozdev.popmungo.logger.logError("Could not log extension info.");
				}
			}
		}
		catch (err) {
			org.mozdev.popmungo.logger.logError(err);
		}
	},
	
	
	logExtensionInfoCallback: function logExtensionInfoCallback(addon) {
		try {
			org.mozdev.popmungo.logger.log(addon.name +" "+ addon.version);
			org.mozdev.popmungo.logger.debug( 
				"\nGUID: "+ addon.id +
				"\nsourceURI: "+ addon.sourceURI.prePath + addon.sourceURI.path +
				"\ninstallDate: "+ addon.installDate +
				"\nupdateDate: "+ addon.updateDate);
		}
		catch (err) {
			org.mozdev.popmungo.logger.logError(err);
		}
	},
	
	
	refreshUI: function refreshUI() {
		org.mozdev.popmungo.logger.setTraceLevelFromPref();
		var enabled = org.mozdev.popmungo.prefs.getPref("extensions.popmungo.enabled", true);

		this.setListener(enabled);
		org.mozdev.popmungo.MenuHandler.setContextMenuListener(enabled);
		this.setStatusbarIcon(enabled);
		this.broadcastState(enabled);

		return enabled;
	},

	
	toggleEnabled: function toggleEnabled() {
		// Toggle state.
		var enabled = !org.mozdev.popmungo.prefs.getPref("extensions.popmungo.enabled", true);
		
		// This triggers observe function.
		org.mozdev.popmungo.prefs.setPref("extensions.popmungo.enabled", enabled);
		
		return enabled;
	},
	

	setListener: function setListener(aEnabled) {
		var appcontent = document.getElementById("appcontent");
		
		if (appcontent) {
			if (aEnabled && !this.listenerEnabled) {
				this.listenerEnabled = true;
				org.mozdev.popmungo.logger.debug("Add DOMContentLoaded listener");
				appcontent.addEventListener("DOMContentLoaded", this, true);
			} else if (!aEnabled && this.listenerEnabled) {
				this.listenerEnabled = false;
				org.mozdev.popmungo.logger.debug("Remove DOMContentLoaded listener");
				appcontent.removeEventListener("DOMContentLoaded", this, true);				
			} else {
				org.mozdev.popmungo.logger.debug('DOMContentLoaded listener enabled='+ this.listenerEnabled);
			}			
		}
	},

	
	onCommand_OptionsMenuitem: function onCommand_OptionsMenuitem() {
		var url = "chrome://popmungo/content/optionsDialog/optionsDialog.xul";
		var features = "alwaysRaised,centerscreen,chrome,titlebar,toolbar,resizable"; // not modal
		
		window.openDialog(url, "PopmungoOptionsDialog", features);
	},
	
	
	onCommand_ToggleEnabledMenuitem: function onCommand_ToggleEnabledMenuitem() {
		this.toggleEnabled();
		return true;
	},
	
	
	onCommand_OpenPopmundoHomepage: function onCommand_OpenPopmundoHomepage(aEvent) {
		org.mozdev.popmungo.logger.debug('Play the game, event='+ aEvent);
		openUILink(org.mozdev.popmungo.commonConstants.GAME_HOMEPAGE, aEvent);
	},


	onCommand_OpenPopmungoHomepage: function onCommand_OpenPopmungoHomepage(aEvent) {
		org.mozdev.popmungo.logger.debug('Visit home page, event='+ aEvent);
		openUILink(org.mozdev.popmungo.commonConstants.EXTENSION_HOMEPAGE, aEvent, false, true);
	},


	onClick_statusbarpanel: function onClick_statusbarpanel(aEvent) {
		org.mozdev.popmungo.logger.debug('button='+ aEvent.button + ', detail='+ aEvent.detail);
		
		if (aEvent.detail == 2) {
			document.getElementById('menupopup_PopmungoStatusBar').hidePopup();
	
			switch (aEvent.button) {
			case 0:
				// Toggle enabled/disabled state
				this.toggleEnabled();
				break;
				
			case 2:
				// Launch options dialog
				//org.mozdev.popmungo.overlay.onCommand_OptionsMenuitem();
				break;
			}
		}
						
		return true;
	},


	setStatusbarIcon: function setStatusbarIcon(aEnabled) {
		// Get status bar panel.
		var sbPanel = document.getElementById("statusbarpanel_Popmungo");
		
		// Set icon.
		if (aEnabled) {
			sbPanel.src = "chrome://popmungo/skin/icon-16x16.png";
			sbPanel.tooltipText = sbPanel.getAttribute('_enabledtooltiptext');
		}
		else {
			sbPanel.src = "chrome://popmungo/skin/icon-16x16-gray.png";
			sbPanel.tooltipText = sbPanel.getAttribute('_disabledtooltiptext');
		}
	},
	
	
	broadcastState: function broadcastState(aEnabled) {
		var broadcaster = document.getElementById("popmungoBc_IsDisabled");
		broadcaster.setAttribute('checked',  !aEnabled);
		broadcaster.setAttribute('disabled', !aEnabled);
		broadcaster.setAttribute('hidden',   !aEnabled);
	},
	
	
	/**
	 * Observe preferences.
	 * 
	 * @param aSubject
	 * @param aTopic
	 * @param aData
	 */
	observe: function observe(aSubject, aTopic, aData)
	{
		org.mozdev.popmungo.logger.debug('topic='+ aTopic +', data='+ aData);
		
		if (aTopic == 'nsPref:changed') {
			this.refreshUI();
		}
	}	
};

org.mozdev.popmungo.overlay = new org.mozdev.popmungo.classes.Overlay();

window.addEventListener("unload", org.mozdev.popmungo.overlay, false);
window.addEventListener("load", org.mozdev.popmungo.overlay, false);

///////////////////////////////////////////////////////////////////////
// EOF
///////////////////////////////////////////////////////////////////////